// 引入 uview 网路 配置项 （官方查看）
const instance = uni.$u.http

// 导入 状态码
import {
  filterNull
} from "@/utils/core/index.js";
// 导入 地址
import {
  app
} from "@/config/app.js";

import {
  transformResponse
} from "./service-utils";

// 平时请求 ---  >  service(config, extraOptions)
// 第一项：网络请求配置项
// 第二项：自定义配置项 
export async function service( {
    url,
    data = {},
    method = "GET",
    headers = {}
  },
  extraOptions = {}
) {
  // 结构出 节流阀：默认true  --- > 表示正在请求当中
  const {
    showLoading = true
  } = extraOptions;

  const token = uni.getStorageSync( 'token' )

  let header = {
    "content-type": "application/json",
    "X-Requested-With": "XMLHttpRequest",
    ...headers
  };
  // 注入token
  if ( token ) {
    header = {
      ...header,
      Authorization: `Bearer ${token}`,
    }

  }
  // 判断 节流阀 --- > 正在请求中 
  if ( showLoading ) {
    uni.showLoading( {
      title: "加载中"
    } );
  }

  const _data = filterNull( data );

  return instance.request( {
      url: app.baseUrl + url,
      method,
      data: _data,
      header
    } )
    .then( response => {
      uni.hideLoading();

      return new Promise( ( resolve, reject ) => {
        try {
          response = transformResponse( response, extraOptions );

          resolve( response.data );
        } catch ( error ) {
          reject( {
            message: error.message
          } );
        }
      } );

    } )
    .catch( err => {
      if ( showLoading ) {
        uni.hideLoading();
      }

      return Promise.reject( err );
    } );
}

//文件上传 可传参
export async function uploadFileParam(
  url,
  filePath,
  data,
  formData = {},
  name = "file"
) {
  Object.keys( data ).forEach( key => {
    formData[ key ] = data[ key ];
  } );
  const token = uni.getStorageSync( 'token' )
  const header = {
    "content-type": "multipart/form-data",
    "X-Requested-With": "XMLHttpRequest"
  };
  if ( token ) {
    header = {
      ...header,
      Authorization: `Bearer ${token}`,
    }
  }
  return instance.uploadFile( {
      url: app.baseUrl + url,
      filePath,
      name,
      formData,
      header
    } )
    .then(
      res => {
        return res.data;
      },
      err => err
    )
    .catch( err => err );
}